<?php
	include_once './init.php';
	include_once './session.php';

	$method = $_POST["method"];
	switch ($method) {
		case 'register':
			register();
			break;
		case 'login':
			login();
			break;
		case 'isLogin':
			if(isLogin()){
				showmsg($login = array(
					'status' => 'login successfully', 
					'loginStatus' => $_SESSION["loginStatus"],
					'userName' => $_SESSION["userName"],
					'userId' => $_SESSION["userId"]
					)
				);
			}else{
				showmsg($login = array(
					'status' => 'login failed'
					)
				);
			};
			break;
		case 'logout':
			sessionEnd();
			break;
	}
	function register(){
		$db = initDatabase();
		$userName = $_POST["userName"];
		$password = $_POST["password"];
		$result = $db -> get_row("select * from user where userName='$userName'");
		if($result){
			//有同样名称的用户
			showmsg('this userName has been used');
		}else{
			$resultOfInsert = $db -> query("insert into user (userName , userPwd) values('$userName' , '$password')");
			
			$resultOfSelect = $db -> get_row("select userId,userName from user where userName='$userName' and userPwd='$password'");
			$userId = $resultOfSelect->userId;
			$userName = $resultOfSelect->userName;
			sessionStart($userId , $userName);
			showmsg('register successfully');
		}
	}
	function login(){
		$db = initDatabase();
		$userName = $_POST["userName"];
		$password = $_POST["password"];
		$result = $db -> get_row("select userId,userName from user where userName='$userName' and userPwd='$password'");
		if($result){
			$userId = $result->userId;
			$userName = $result->userName;
			sessionStart($userId , $userName);
			showmsg($login = array(
				'status' => 'login successfully', 
				'loginStatus' => $_SESSION["loginStatus"],
				'userId' => $_SESSION["userId"],
				'userName' => $_SESSION["userName"]
				)
			);
		}else{
			showmsg('fail to login');
		}
	}
?>
